import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'jpush_service.dart';

class HttpClient {
  late final Dio _dio;

  // 根据环境动态设置baseUrl
  late final String _baseUrl;
  
  // 初始化baseUrl
  String _initBaseUrl() {
    // 在调试模式下使用内网环境
    if (kDebugMode) {
      return 'http://192.168.110.159:8080';
      // return 'http://118.196.25.232:8080';
    }
    // 在发布模式下使用服务器地址
    else {
      return 'http://118.196.25.232:8080';
    }
  }
  final Duration _timeout = const Duration(seconds: 10);

  final List<String> _whiteList = [
    '/auth/smsCode',
    '/auth/loginBySms',
  ];

  HttpClient() {
    _baseUrl = _initBaseUrl();
    _initDio();
  }

  void _initDio() {
    _dio = Dio(BaseOptions(
      baseUrl: _baseUrl,
      connectTimeout: _timeout,
      receiveTimeout: _timeout,
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
      },
    ));

    // 暂时注释掉详细日志拦截器
    // if (kDebugMode) {
    //   _dio.interceptors.add(LogInterceptor(
    //     requestBody: true,
    //     responseBody: true,
    //   ));
    // }

    _dio.interceptors.add(InterceptorsWrapper(
      onRequest: (options, handler) async {
        final isWhiteListed =
            _whiteList.any((path) => options.path.contains(path));
        if (!isWhiteListed) {
          final token = await _getToken();
          if (token != null && token.isNotEmpty) {
            options.headers['Authorization'] = 'Bearer $token';
          } else {
          }
        } else {
        }
        handler.next(options);
      },
      onResponse: (response, handler) {
        final data = response.data;

        if (data is Map<String, dynamic>) {
          final code = data['code'] ?? -1;
          final msg = data['msg']?.toString();

          if (code == 200) {
            handler.next(response);
          } else {
            handler.reject(
              DioException(
                requestOptions: response.requestOptions,
                response: response,
                type: DioExceptionType.badResponse,
                error: msg ?? '业务请求失败',
              ),
            );
          }
        } else {
          handler.next(response);
        }
      },
      onError: (DioException e, handler) {
        String errorMsg = '网络请求失败';

        switch (e.type) {
          case DioExceptionType.connectionTimeout:
            errorMsg = '连接超时';
            break;
          case DioExceptionType.sendTimeout:
            errorMsg = '请求发送超时';
            break;
          case DioExceptionType.receiveTimeout:
            errorMsg = '响应接收超时';
            break;
          case DioExceptionType.badResponse:
            final statusCode = e.response?.statusCode;
            errorMsg = '服务器响应错误 [$statusCode]';
            break;
          case DioExceptionType.cancel:
            errorMsg = '请求已取消';
            break;
          case DioExceptionType.badCertificate:
            errorMsg = '证书验证失败';
            break;
          case DioExceptionType.connectionError:
            errorMsg = '连接错误';
            break;
          case DioExceptionType.unknown:
            errorMsg = e.message ?? '未知错误';
            break;
        }

        handler.reject(
          DioException(
            requestOptions: e.requestOptions,
            response: e.response,
            type: e.type,
            error: errorMsg,
          ),
        );
      },
    ));
  }

  // GET
  Future<dynamic> get(String path,
      {Map<String, dynamic>? queryParameters}) async {
    try {
      final response = await _dio.get(path, queryParameters: queryParameters);
      // 暂时注释掉GET日志
      return response.data;
    } on DioException catch (e) {
      throw e.error ?? 'GET 请求失败';
    }
  }

  // POST
  Future<dynamic> post(String path,
      {dynamic data, Map<String, dynamic>? queryParameters}) async {
    try {
      final response =
          await _dio.post(path, data: data, queryParameters: queryParameters);
      return response.data;
    } on DioException catch (e) {
      throw e.error ?? 'POST 请求失败';
    }
  }

  // PUT
  Future<dynamic> put(String path,
      {dynamic data, Map<String, dynamic>? queryParameters}) async {
    try {
      final response =
          await _dio.put(path, data: data, queryParameters: queryParameters);
      return response.data;
    } on DioException catch (e) {
      throw e.error ?? 'PUT 请求失败';
    }
  }

  // DELETE
  Future<dynamic> delete(String path,
      {Map<String, dynamic>? queryParameters}) async {
    try {
      final response =
          await _dio.delete(path, queryParameters: queryParameters);
      return response.data;
    } on DioException catch (e) {
      throw e.error ?? 'DELETE 请求失败';
    }
  }

  // 获取 Token
  Future<String?> _getToken() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final token = prefs.getString('access_token');
      // 暂时注释掉Token日志
      return token;
    } catch (e) {
      return null;
    }
  }

// 保存 Token
  Future<void> saveToken(String token) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString('access_token', token);
      await JPushService().init(); 
    } catch (e) {
    }
  }

// 清除 Token（暴露为公共方法）
  Future<void> clearToken() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.remove('access_token');
    } catch (e) {
    }
  }
}
